package infraestructura;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import modelo.Comment;

public class CommentPoolPersistence implements CommentPersistence {

    private DataSource pool = null;
    private static CommentPoolPersistence persistence = null;

    private CommentPoolPersistence() {
        Context env = null;
        try {
            env = (Context) new InitialContext().lookup("java:comp/env");
            pool = (DataSource) env.lookup("jdbc/ShoppersPool");
            if (pool == null) {
                throw new RuntimeException("No se ha podido obtener la conexion");
            }
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }

    public static CommentPersistence getPersistenceManager() {
        if (persistence == null) {
            persistence = new CommentPoolPersistence();
        }
        return persistence;
    }

    @Override
    public void addComment(Comment comment) {
        Connection conexion = null;
        PreparedStatement statement = null;
        try {
            conexion = pool.getConnection();
            statement = conexion.prepareStatement("SELECT comentario_id "
                    + "FROM comentario "
                    + "ORDER BY comentario_id DESC;");

            ResultSet resultSet = statement.getResultSet();
            resultSet.first();
            int id;
            if (resultSet.getRow() != 0) {
                id = resultSet.getInt("comentario_id");
            } else {
                id = 0;
            }
            id++;
            statement.close();

            statement = conexion.prepareStatement("INSERT INTO `shoppers`.`comentario`"
                    + "(`Comentario_Id`, `Comentario_texto`, `Producto_Id`) VALUES"
                    + "(?, '?', ?);");
            statement.setInt(1, id);
            statement.setString(2, comment.getComment());
            statement.setInt(3, comment.getProductId());

            statement.executeUpdate();
                        
        } catch (SQLException ex) {
            Logger.getLogger(CommentPoolPersistence.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (conexion != null) {
                try {
                    conexion.close();
                } catch (SQLException ex) {
                    Logger.getLogger(CommentPoolPersistence.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    if (statement != null) {
                        try {
                            statement.close();
                        } catch (SQLException ex) {
                            Logger.getLogger(CommentPoolPersistence.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }


    }

    @Override
    public List<Comment> getCommentsForProduct(int productId) {
        List<Comment> commentsForProduct = new ArrayList();

        Connection conexion = null;
        PreparedStatement statement = null;
        try {
            conexion = pool.getConnection();
            statement = conexion.prepareStatement("SELECT comentario_texto, producto_id "
                    + "FROM comentario "
                    + "WHERE producto_id = ?;");

            statement.setInt(1, productId);

            statement.execute();
            ResultSet resultSet = statement.getResultSet();

            while (resultSet.next()) {
                String texto = resultSet.getString("comentario_texto");
                int idProducto = resultSet.getInt("producto_id");
                commentsForProduct.add(new Comment(idProducto, texto));
            }

            return commentsForProduct;
        } catch (SQLException ex) {
            Logger.getLogger(CommentPoolPersistence.class.getName()).log(Level.SEVERE, null, ex);
            //@Abraham Aqui sí que está bien hecho
        } finally {
            if (conexion != null) {
                try {
                    conexion.close();
                } catch (SQLException ex) {
                    Logger.getLogger(CommentPoolPersistence.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    if (statement != null) {
                        try {
                            statement.close();
                        } catch (SQLException ex) {
                            Logger.getLogger(CommentPoolPersistence.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }
        return null;
    }
}